from emmodels.em_his_series import ModuleHisSeries
from emmodels.em_base_data import ModuleBaseData
import tushare as ts
import datetime

module_all = ModuleBaseData.select_all()

l = []
for item in module_all:
    begin = datetime.datetime.now()
    code = item.moduleid
    name = item.module_name

    last_his = ModuleHisSeries.select_last(code)
    start_date = None
    start = None
    if last_his and last_his.datatime:
        start_date = min(last_his.datatime, datetime.datetime.now())
        start = start_date.strftime("%Y-%m-%d")
    else:
        start = '1990-01-01'

    end = begin.strftime("%Y-%m-%d")

    m1 = ts.get_k_data(code=code, start=start, end=end, pause=0.1, ktype='M', autype='qfq',index=True)
    m_his_series = [ModuleHisSeries(stockid=code, datatime=his[0], open=his[1], close=his[2], high=his[3], low=his[4], volume=his[5],period='M') for his in m1.values]
    l.extend(m_his_series)

    w1 = ts.get_k_data(code=code, start=start, end=end, pause=0.1, ktype='W', autype='qfq',index=True)
    w_his_series = [ModuleHisSeries(stockid=code, datatime=his[0], open=his[1], close=his[2], high=his[3], low=his[4], volume=his[5], period='W') for his in w1.values]
    l.extend(w_his_series)

    d1 = ts.get_k_data(code=code, start=start, end=end, pause=0.1, ktype='D', autype='qfq',index=True)
    d_his_series = [ModuleHisSeries(stockid=code, datatime=his[0], open=his[1], close=his[2], high=his[3], low=his[4], volume=his[5], period='D') for his in d1.values]
    l.extend(d_his_series)

    if len(l) >0:
        ModuleHisSeries.insert_list(l,append_dup_list=['stockid', 'datatime', 'period'])
        print('插入%s(%s)所有从%s到%s这段时间周期数据,耗时%d秒' % (name, code, start, end, (datetime.datetime.now() - begin).seconds))
    else:
        print("无数据同步")
    l.clear()
